﻿using System.Windows;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using LottieDemo.Services;
using LottieDemo.Services.Interfaces;
using LottieDemo.ViewModels;
using LottieDemo.Views;
using Serilog;

namespace LottieDemo;

/// <summary>
/// 应用程序入口
/// </summary>
public partial class App : Application
{
    private IHost? _host;

    /// <summary>
    /// 应用程序启动时配置Host
    /// </summary>
    protected override async void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        // 配置Serilog
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Information()
            .WriteTo.Console()
            .WriteTo.File("logs/chatdemo-.log", rollingInterval: RollingInterval.Day)
            .CreateLogger();

        try
        {
            // 构建Host
            _host = Host.CreateDefaultBuilder()
                .UseSerilog()
                .ConfigureServices((context, services) =>
                {
                    // 注册主窗口
                    services.AddSingleton<MainWindow>();

                    // 注册ViewModels
                    services.AddSingleton<ChatViewModel>();

                    // 注册服务
                    services.AddSingleton<IAiChatService, AiChatService>();
                })
                .Build();

            await _host.StartAsync();

            // 从DI容器获取主窗口并显示
            var mainWindow = _host.Services.GetRequiredService<MainWindow>();
            mainWindow.Show();
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "应用程序启动失败");
            MessageBox.Show($"应用程序启动失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            Shutdown();
        }
    }

    /// <summary>
    /// 应用程序退出时清理资源
    /// </summary>
    protected override async void OnExit(ExitEventArgs e)
    {
        if (_host != null)
        {
            await _host.StopAsync();
            _host.Dispose();
        }

        Log.CloseAndFlush();
        base.OnExit(e);
    }
}

